<template>
  <div class="container">
    <uv-form labelPosition="top" :model="model" :rules="rules" ref="form" labelWidth="300" :labelStyle="labelStyle">
      <view v-for="(item, index) in info" :key="index">
        <uv-form-item :label="dict_format(item)" v-if="item.fieldName=='enterprise'" :prop="item.fieldName" borderBottom>
          <view class="positionRelative width100">
            <uv-input @clear="enterpriseJurisdictionClear" :placeholder="`请输入${dict_format(item)}`" :disabled="isDisabled(item.fieldName)" v-model="model[item.fieldName]" inputAlign="left" border="none" @input="handleInput" clearable></uv-input>
            <view class="enterpriseWrap" v-if="showEnterprise">
              <view class="box" @click="enterpriseClick(el)" v-for="(el, idx2) in enterpriseList" :key="idx2">
                <view class="fz14 bold">{{el.qymc}}</view>
                <view class="fz12 desc">{{el.dz}}</view>
              </view>
            </view>
          </view>
        </uv-form-item>
        <!-- 输入框 -->
        <uv-form-item :label="dict_format(item)" v-else-if="item.type=='input'" :prop="item.fieldName" borderBottom>
          <!-- @click="instance.refs.areasPicker.open()" -->
          <view class="width100 flex" v-if="item.fieldName=='enterpriseJurisdiction'">
            <!-- <uv-input readonly placeholderStyle="textAlign:left;color:#C0C4CC" inputAlign="left" v-model="model[item.fieldName]" border="none" :placeholder="`请输入${dict_format(item)}`" clearable></uv-input> -->
            <uv-input placeholder="请输入xx市" v-model="model.city"><template v-slot:suffix>市</template></uv-input>
            <uv-input placeholder="请输入xx区" v-model="model.district"><template v-slot:suffix>区</template></uv-input>
          </view>
          <uv-input v-else placeholderStyle="textAlign:left;color:#C0C4CC" inputAlign="left" v-model="model[item.fieldName]" border="none" :placeholder="`请输入${dict_format(item)}`" :disabled="isDisabled(item.fieldName)"></uv-input>
        </uv-form-item>
        <!-- 下拉选择 -->
        <uv-form-item :label="dict_format(item)" v-else-if="item.type=='select'" :prop="item.fieldName" borderBottom>
          <view class="width100" @click="itemClick(item)">
            <uv-input placeholderStyle="textAlign:left;color:#C0C4CC" inputAlign="left" v-model="model[item.fieldName]" border="none" :placeholder="`请输入${dict_format(item)}`" readonly :disabled="isDisabled(item.fieldName)"></uv-input>
          </view>
        </uv-form-item>
        <!-- 照片 -->
        <uv-form-item :label="dict_format(item)" v-else-if="item.type=='image'" :prop="item.fieldName" borderBottom>
          <uploader :maxCount="9" v-model="model[item.fieldName]"></uploader>
        </uv-form-item>
        <!-- 文件上传 -->
        <uv-form-item :label="dict_format(item)" v-else-if="item.type=='file'" :prop="item.fieldName" borderBottom>
          <uploaderFile v-model="model[item.fieldName]"></uploaderFile>
        </uv-form-item>
        <!-- 关联性 -->
        <uv-form-item :label="dict_format(item)" v-else-if="item.type=='relation'" :prop="item.fieldName" borderBottom>
          <uv-radio-group v-model="model[item.fieldName]" placement="column">
            <uv-radio :customStyle="{margin: '8px'}" v-for="(ele,idx) in relationJsonArr(item.defaultValueTableChildren)" :key="idx" :value="ele.title" :name="ele.title" @change="handleRadioChange(item,idx)">
              <view>
                <view class="title fz14">{{ele.title}}</view>
                <view class="intro fz12" style="color:#2A84A0">{{label_format(ele.intro)}}</view>
              </view>
            </uv-radio>
          </uv-radio-group>
        </uv-form-item>
      </view>
    </uv-form>

    <uv-form labelPosition="top" v-if="relationList&&relationList.length" :labelWidth="counter.windowWidth-30">
      <uv-form-item :label="row.title" v-for="(row,index) in relationList" :key="index">
        <view>
          <uv-parse :content="row.intro" v-if="row.intro"></uv-parse>
          <uploader :maxCount="9" v-model="row.value" v-if="row.type=='image'"></uploader>
          <view class="links" v-else-if="row.type=='templateFile'">
            <view class="link" v-for="(el,idx) in proxy.$utils.deepcopy(row.file)" :key="idx">
              <!-- #ifdef MP-WEIXIN -->
              <view class="flex alignCenter">
                <uv-text type="primary" :text="el.name" decoration="underline" @click="proxy.$auth.openDocument(el.path)"></uv-text>
                <view @click="proxy.$auth.saveFile(el.path)">
                  <uv-icon name="download"></uv-icon>
                </view>
              </view>
              <!-- #endif -->

              <!-- #ifdef H5 -->
              <uv-link :href="el.path" :text="el.name" :under-line="true"></uv-link>
              <!-- #endif -->
            </view>
            <view class="uploaderFile">
              <uploaderFile v-model="row.value"></uploaderFile>
            </view>
          </view>
          <view v-else-if="row.type=='file'">
            <uploaderFile v-model="row.value"></uploaderFile>
          </view>
        </view>
      </uv-form-item>
    </uv-form>

    <uvPicker2 :placeholderStyle="{textAlign:'left',color:'#C0C4CC'}" :placeholder="`请输入${dict_format({'fieldName':fieldName})}`" :columns="[columns]" ref="pickerRef" v-model="model[fieldName]" v-if="fieldName"></uvPicker2>

    <uv-picker ref="areasPicker" :columns="[areas]" @confirm="confirmArea" keyName="name"></uv-picker>

    <view class="actionBtn">
      <uv-button shape="circle" text="提交" color="#4196A2" :loading="loading" @click="submit"></uv-button>
    </view>
  </div>
</template>

<script setup lang="ts">
import uploaderFile from "@/components/uv/uploaderFile.vue";
import uploader from "@/components/uv/uploader.vue";
import uvPicker2 from "@/components/uv/uvPicker.vue";
const { proxy } = getCurrentInstance();
import useCounterStore from "@/stores/counter";
const counter = useCounterStore();
const instance = getCurrentInstance();

let disabledList = computed(() => {
  let arr = ["enterpriseTax"];
  let resp = counter.ycMpParams.userInfo;
  if (resp.baseInfo) {
    if (resp.baseInfo.name) arr.push("name");
    if (resp.baseInfo.mobile) arr.push("mobile");
    if (resp.baseInfo.identityCard) arr.push("identityCard");
  }
  if (
    model.value.hasOwnProperty("employed_Status") &&
    model.value.employed_Status.includes("未")
  ) {
    arr.push("enterprise");
  }
  return arr;
});

const validateMobile = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("请输入联系方式"));
  } else if (!proxy.$utils.isPoneAvailable(value)) {
    callback(new Error("请输入正确的联系方式"));
  } else {
    callback();
  }
};

const validateIdCard = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("请输入身份证号"));
  } else if (proxy.$utils.isIdCard(value) != 0) {
    callback(new Error("请输入正确的身份证号"));
  } else {
    callback();
  }
};

let placeholderStyle = computed(() => {
  return {
    textAlign: "left",
  };
});

let labelStyle = computed(() => {
  return { fontWeight: "bold" };
});

let areas = ref([]); //地址
let fieldName = ref("");
let relationList = ref([]); //关系列表
let loading = ref(false);
let columns = ref([]);
let showEnterprise = ref(false); //是否显示企业列表
let enterpriseList = ref([]); //企业列表
let curriculumData = {};
let info = ref({});
let model = ref({});
let dicts = ref({});
let rules = ref({
  mobile: [{ required: true, validator: validateMobile, trigger: "blur" }],
  identityCard: [
    { required: true, validator: validateIdCard, trigger: "blur" },
  ],
  education: [{ required: true, message: "请输入学历", trigger: "blur" }],
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  school: [{ required: true, message: "请输入毕业院校", trigger: "blur" }],
  graduationMajor: [
    { required: true, message: "请输入毕业专业", trigger: "blur" },
  ],
  workYears: [
    { required: true, message: "请输入累计工作年限", trigger: "blur" },
  ],
  conditions: [{ required: true, message: "请设置报名条件", trigger: "blur" }],
  // enterprise: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
  // enterpriseTax: [
  //   { required: true, message: "请设置所在企业税号", trigger: "blur" },
  // ],
  enterpriseJurisdiction: [
    { required: true, message: "请设置所在企业区属", trigger: "blur" },
  ],
  employed_Status: [
    { required: true, message: "请设置当前就业状态", trigger: "blur" },
  ],
  identification_scancopy: [
    {
      required: true,
      // 自定义验证函数，见上说明，注意这里面的逻辑不能出现语法报错，否则可能导致不验证
      validator: (rule, value, callback) => {
        return !(value.length == 0);
      },
      message: "请上传您的《身份证》正反面扫描件",
      trigger: ["blur", "change"],
    },
  ],
  certificate_scancopy: [
    {
      required: true,
      // 自定义验证函数，见上说明，注意这里面的逻辑不能出现语法报错，否则可能导致不验证
      validator: (rule, value, callback) => {
        return !(value.length == 0);
      },
      message: "请上传您的《毕业证书》扫描件",
      trigger: ["blur", "change"],
    },
  ],
  "conditions-3rd-grade": [
    {
      required: true,
      message: "请选择您的三级报考条件",
      trigger: "blur",
    },
  ],
  "conditions-4rd-grade": [
    {
      required: true,
      message: "请选择您的四级报考条件",
      trigger: "blur",
    },
  ],
});

onLoad(() => {
  init();
});

let canRequired = computed(() => {
  if (model.value.employed_Status && model.value.employed_Status.includes("未"))
    return false;
  return true;
});

function confirmArea(e) {
  model.value.enterpriseJurisdiction = e.value[0].name;
}

function isDisabled(e) {
  return disabledList.value.includes(e);
}

function relationJsonArr(array) {
  let arr = [];
  array.forEach((element) => {
    if (!element.parentId) arr.push(element);
  });
  return arr;
}

function label_format(e) {
  if (!e) return;
  let arr = [];
  arr = getChineseCharacters(e);
  let str = "";
  if (arr.length) {
    arr.forEach((element) => {
      str += element;
    });
    return str;
  }
}

function getChineseCharacters(str) {
  const chineseRegex = /[\u4e00-\u9fa5]/g; // 匹配中文字符的正则表达式
  const chineseCharacters = str.match(chineseRegex); // 使用正则表达式匹配中文字符
  return chineseCharacters;
}

function itemClick(item) {
  if (isDisabled(item.fieldName)) return;
  if (item.defaultValue.includes(",")) {
    columns.value = item.defaultValue.split(",");
  } else {
    columns.value = item.defaultValue.split(";");
  }
  fieldName.value = item.fieldName;
  setTimeout(() => {
    instance.refs.pickerRef && instance.refs.pickerRef.open();
  }, 300);
}

function dict_format(params) {
  if (!dicts.value.length) return;
  let index = proxy.$utils.findIndexByField(
    dicts.value,
    "dict_code",
    params.fieldName
  );
  if (index != -1) return dicts.value[index].dict_label;
}

function init() {
  //下单
  if (proxy.$utils.isEmptyObject(counter.orderDetails)) {
    placeOrder();
  } else {
    //编辑订单信息
    editInfo();
  }
  getDict();
  getAddress();
}

async function getAddress() {
  let resp = await proxy.$atlas.getAreas("上海市", 2);
  areas.value = resp[0].districts[0].districts;
  //console.log("省市区", areas.value);
}

async function editInfo() {
  let item = proxy.$utils.deepcopy(counter.orderDetails);
  model.value = { ...item.approvalContent.model };
  let resp = await proxy.$apis.webCourse({
    type: "details",
    data: { _id: item.curriculum_id },
  });
  if (resp.needUserParams && resp.needUserParams.length) {
    info.value = resp.needUserParams;
  }
  relationList.value = item.approvalContent.relationList;
}

async function needUserParams(array) {
  let dicts = await proxy.$apis.dicts({
    type: "query",
    data: { name: "用户信息" },
  });
  let ruleList = proxy.$utils.deepcopy(rules.value);
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    if (element.type == "input") {
      if (!ruleList.hasOwnProperty(element.fieldName)) {
        let current = proxy.$utils.findIndexByField(
          dicts,
          "dict_code",
          element.fieldName
        );
        rules.value[element.fieldName] = [
          {
            required: true,
            message: `请输入${dicts[current].dict_label}`,
            trigger: "blur",
          },
        ];
      }
    }
  }
}

async function placeOrder() {
  curriculumData = proxy.$utils.deepcopy(counter.ycMpParams.curriculumInfo);
  if (
    curriculumData["needUserParams"] &&
    curriculumData["needUserParams"].length
  ) {
    needUserParams(curriculumData["needUserParams"]);
    info.value = [...curriculumData["needUserParams"]];
    info.value.forEach((element) => {
      model.value[element.fieldName] = element.value;
    });
  }
  //如果之前有维护过个人信息
  if (counter.ycMpParams.userInfo.baseInfo) {
    //console.log("个人信息", counter.ycMpParams.userInfo.baseInfo);
    model.value = proxy.$utils.formatFunction(
      counter.ycMpParams.userInfo.baseInfo,
      { ...model.value }
    );
    if (model.value.hasOwnProperty("enterpriseJurisdiction")) {
      if (counter.ycMpParams.userInfo.baseInfo.city) {
        model.value.city = counter.ycMpParams.userInfo.baseInfo.city;
        model.value.district = counter.ycMpParams.userInfo.baseInfo.district;
      }
    }
    if (model.value["conditions-3rd-grade"])
      model.value["conditions-3rd-grade"] = "";
    if (model.value["conditions-4th-grade"])
      model.value["conditions-4th-grade"] = "";
  }
  //console.log("下单信息", model.value);
}

async function getDict() {
  let { data } = await proxy.$apis.getDict({
    type: "details",
    data: {
      code: "user_info",
    },
  });
  dicts.value = data;
}

async function handleInput(e) {
  enterpriseList.value = await proxy.$apis.autoMatchCompany({
    key: e,
  });
  if (enterpriseList.value.length) {
    if (enterpriseList.value.length == 1) {
      enterpriseClick(enterpriseList.value[0]);
    } else {
      showEnterprise.value = true;
    }
  }
}

function enterpriseJurisdictionClear() {
  if (model.value.hasOwnProperty("enterpriseJurisdiction")) {
    model.value.enterpriseJurisdiction = "";
    model.value.city = "";
    model.value.district = "";
  }
}

function enterpriseClick(e) {
  let obj = {};
  obj["enterprise"] = e.qymc;

  if (model.value.hasOwnProperty("enterpriseTax"))
    obj["enterpriseTax"] = e.nsrsbh;
  //所属区属
  if (model.value.hasOwnProperty("enterpriseJurisdiction")) {
    let resp = extractAddressInfo(e.dzdh);
    if (resp && resp.province) {
      obj["enterpriseJurisdiction"] = resp.province + resp.city + resp.district;
    } else {
      obj["enterpriseJurisdiction"] = "";
    }
  }
  model.value = proxy.$utils.formatFunction({ ...obj }, { ...model.value });
  showEnterprise.value = false;

  function extractAddressInfo(address) {
    if (!address) return {};
    const regex = /(.*省|.*自治区)?(.*市)?(.*区|.*县)?/;
    const matches = address.match(regex);
    if (address.includes("市") && address.includes("区")) {
      let province = matches[1] ? matches[1].trim() : "";
      let city = matches[2] ? matches[2].trim() : "";
      let district = matches[3] ? matches[3].trim() : "";

      return { province, city, district };
    } else {
      // 如果没有找到省市，返回第一个区之前的字符串
      const firstDistrictIndex = address.indexOf("区");
      if (firstDistrictIndex !== -1) {
        let aa = address.substring(0, firstDistrictIndex);
        return { province: "", city: "", district: aa };
      }
    }
  }
}

function handleRadioChange(item, index) {
  relationList.value = [];
  let list = proxy.$utils.transformArray(
    [...item.defaultValueTableChildren],
    "id",
    "parentId"
  );
  relationList.value = proxy.$utils.deepcopy(list[index].children);
  console.log("relationList", relationList.value);
}

async function submit() {
  // 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
  // console.log("model.value", model.value);
  // console.log("rule", rules.value);
  instance.refs.form
    .validate()
    .then((res) => {
      save();
    })
    .catch((errors) => {
      if (errors.length) proxy.$utils.showToast(errors[0].message);
      console.log("errors", errors);
    });
}

async function save() {
  try {
    loading.value = true;
    if (model.value.hasOwnProperty("enterpriseJurisdiction")) {
      if (!model.value.city) return proxy.$utils.showToast("请输入学员所在市");
      if (!model.value.district)
        return proxy.$utils.showToast("请输入学员所在区");
    }
    //如果有学员工作状态 && 选择未就业
    if (
      model.value.employed_Status &&
      model.value.employed_Status.includes("未")
    ) {
    } else if (
      model.value.hasOwnProperty("enterprise") &&
      !model.value.enterprise
    ) {
      return proxy.$utils.showToast("请选择所在企业");
    }
    if (relationList.value.length) {
      for (let index = 0; index < relationList.value.length; index++) {
        const element = relationList.value[index];
        if (element.hasOwnProperty("value")) {
          if (!element.value || !element.value.length)
            return proxy.$utils.showToast(element.title);
        } else {
          return proxy.$utils.showToast(element.title);
        }
      }
    }
    await proxy.$apis.student({
      data: model.value,
      type: "perfect",
    });
    if (proxy.$utils.isEmptyObject(counter.orderDetails)) {
      await newOrder();
    } else {
      await againSendOrder({
        model: model.value,
        relationList: relationList.value,
      });
    }
  } catch (error) {
  } finally {
    setTimeout(() => {
      loading.value = false;
    }, 1200);
  }
}

//重新提交审核材料
async function againSendOrder(obj) {
  await proxy.$apis.orderAction({
    type: "update",
    data: {
      approvalContent: {
        model: obj.model,
        relationList: obj.relationList,
      },
      status: 1,
      rejectMsg: "",
      orderId: counter.orderDetails._id,
    },
  });
  proxy.$utils.showToast("重新提交成功");
  proxy.$utils.toLink(`/packagePages/order/list`, "redirectTo");
  counter.orderDetails = {};
}

//创建新订单
async function newOrder() {
  let obj = {
    approvalContent: {
      //审批内容
      model: model.value,
      relationList: relationList.value,
      selectLesson: curriculumData["selectLesson"], //选择的课程
    },
    curriculum_id: curriculumData["_id"], //课程 id
    price: curriculumData["newPrice"] //报名金额
      ? curriculumData["newPrice"]
      : curriculumData["price"],
    mobile: model.value.mobile, //手机号
  };
  let payType = "H5";
  // #ifdef MP-WEIXIN
  payType = "MP-WEIXIN";
  // #endif
  obj["payType"] = payType;
  //如果有预报名金额
  if (curriculumData["signUpPrice"])
    obj["signUpPrice"] = curriculumData["signUpPrice"];

  if (obj.hasOwnProperty("signUpPrice") || Number(obj.price)) {
    let resp = await proxy.$apis.createOrder(obj);
    await proxy.$pay.pay(resp);
    proxy.$utils.showToast("支付成功", 1);
  } else {
    await proxy.$apis.createFreeOrder(obj);
    proxy.$utils.showToast("报名成功");
    setTimeout(() => {
      proxy.$utils.toLink(`/packagePages/order/list`, "redirectTo");
    }, 1200);
  }
}

watch(
  () => model.value.employed_Status,
  (newValue, oldValue) => {
    let arr = ["enterprise", "enterpriseTax"];
    if (newValue && newValue.includes("未")) {
      arr.forEach((element) => {
        model.value[element] = "";
      });
      delete rules.value.enterprise;
      delete rules.value.enterpriseTax;
    } else {
      if (!rules.value.enterprise) {
        rules.value["enterprise"] = [
          { required: true, message: "请输入企业名称", trigger: "blur" },
        ];
        rules.value["enterpriseTax"] = [
          { required: true, message: "请设置所在企业税号", trigger: "blur" },
        ];
      }
    }
  },
  { immediate: true, deep: true }
);

watch(
  () => [model.value.city, model.value.district],
  (newValue, oldValue) => {
    if (model.value.city && model.value.district) {
      model.value.enterpriseJurisdiction = `${model.value.city}${model.value.district}`;
    }
  },
  { immediate: true, deep: true }
);
</script>



<style lang="scss" scoped>
.container {
  padding: 15px 15px 90px 15px;
  .enterpriseWrap {
    position: absolute;
    left: 0;
    z-index: 99999;
    background-color: white;
    padding: 10px;
    box-shadow: 2px 5px 5px 2px #cfcfcf;
    border-radius: 10px;
    .box {
      margin-bottom: 10px;
      .desc {
        color: #999999;
      }
    }
  }
  ::v-deep .uv-form-item {
    .uv-form-item__body__left__message {
      text-align: left;
    }
  }
  .links {
    .link {
      margin-top: 15px;
    }
    .uploaderFile {
      margin-top: 20px;
    }
  }
  .actionBtn {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 15px 15px 25px 15px;
    background-color: white;
    z-index: 10;
  }
}
</style>



